/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.tasks
{
	/**
	 * Function call task.  This is a special task that calls a callback function and ends immediately after.
	 * 
	 * @example This example will wait 0.5 secs, execute someFunction with no arguments, then wait another 0.5 secs, and finally trace "Done.":
	 * <listing version="3.0">
	 * 	tasks.add(
	 * 		new Sequence(
	 *			new Wait(500),
	 * 			new Func(someFunction),
	 *			new Wait(500),
	 * 			new Func(trace, "Done."),
	 * 		)
	 * 	)
	 * </listing>
	 *
	 * @see TaskRunner
	 */
	public class Func extends Task
	{
		private var callback:Function;
		private var args:Array;

		/**
		 * Create a Func task.
		 *
		 * @param callback The callback function.
		 * @param rest The arguments that will be passed to the callback function.
		 */
		public function Func(callback:Function, ... rest)
		{
			super();
			this.callback = callback;
			this.args = rest;
		}
		
		/**
		 * Utility function to create a Func task from an arguments array.
		 *
		 * @param callback The callback function.
		 * @param args The arguments that will be passed to the callback function.
		 */
		public static function fromArgsArray(callback:Function, args:Array):Func
		{
			var f:Func = new Func(callback);
			f.args = args;
			return f;
		}
		
		/** @inheritDoc */
		public override function clone():ITask
		{
			return fromArgsArray(callback, this.args);
		}

		/**
		 * @inheritDoc
		 */
		public override function start():void
		{
			super.start();
			if (this.callback != null) 
				this.callback.apply(null, this.args);
			this.taskComplete();
		}
	}
}
